import "./FormView.less"; // 需前置 否则组件中设置的部分样式会低于wea-edc-form-item的相关样式
import React from "react";
import Error from "./pane/Error";
import Success from "./pane/Success";
import {WeaLocaleProvider} from "ecCom";
import FormMainView from "./Main";
import {observer} from "mobx-react";
import {findDOMNode} from "react-dom";
import {errorTypes, viewTypes} from "../../../../constants/form";
import FBHeaderView from "../component/form-header/View";
import {Consumer} from "../theme";

const getLabel = WeaLocaleProvider.getLabel;

const { PC } = viewTypes;

@observer
export default class FormView extends React.Component {
  constructor(props) {
    super();

    this.store = props.store;
  }

  componentDidUpdate() {
    const { errorCom, resetErrorCom } = this.store;

    if (errorCom) {
      const { errorCom: subErrorCom } = errorCom;
      const wrapperDOM = findDOMNode(this.wrapper);
      const errorComDOM = wrapperDOM.querySelector(`[data-id='${errorCom.uuid}']`);
      const subErrorComDOM = subErrorCom && wrapperDOM.querySelector(`[data-id='${subErrorCom.uuid}']`);

      this.scrollToError(errorComDOM);
      this.autoFocus(subErrorComDOM || errorComDOM);
      resetErrorCom();
    }
  }

  scrollToError(errorComDOM) {
    if (errorComDOM) { 
      const offset = errorComDOM.offsetParent.offsetTop;
      this.scrollSmoothTo(offset);
      //errorComDOM.scrollIntoView({block: 'center', behavior: 'smooth'}); 
    }
  }

  scrollSmoothTo(position) {
    if (!window.requestAnimationFrame) {
        window.requestAnimationFrame = function(callback, element) {
            return setTimeout(callback, 17);
        };
    }
    let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
    let step = function () {
        // 距离目标滚动距离
        let distance = position - scrollTop;
        // 目标滚动位置
        scrollTop = scrollTop + distance / 5;
        if (Math.abs(distance) < 1) {
            window.scrollTo(0, position);
        } else {
            window.scrollTo(0, scrollTop);
            requestAnimationFrame(step);
        }
    };
    step();
  }

  autoFocus(errorComDOM) {
    const focusEle = errorComDOM.querySelector('select, input, textarea');

    if (focusEle) focusEle.focus();
  }

  render() {
    const {
      formHeader, formFooter, components, success, error, shortkey, viewType,
      onSubmit, onValueChange, rightLevel, toggleFooterDisable
    } = this.store;

    if (success) {
      return (
        <Consumer>
          {({background}) => (
            <div className={`wea-edc-pane-box ${(viewType != PC && background.type == 0) ? 'wea-edc-fv-wrapper-mobilebg' : ''}`}
                 style={(viewType != PC && background.type == 0) && {} || background.css}
            >
              <Success title={formHeader && formHeader.config.title} shortkey={rightLevel === 2 ? shortkey : ""} />
            </div>
          )}
          </Consumer>
      )
    }

    if (error && error.msg_type === errorTypes.PAGE) {
      return <Error msg={error.api_errormsg}/>;
    }

    return (
      <Consumer>
        {({background, form}) => (
          <div className={`wea-edc-fv-wrapper ${viewType === PC ? '' : 'mobile-device' + ' ' + (background.type == 0 ? 'wea-edc-fv-wrapper-mobilebg' : '') + ' ' + (form.mFullWidth ? 'wea-edc-fv-wrapper-mobilefull' : '') }`}
            ref={wrapper => this.wrapper = wrapper}
             style={(viewType != PC && background.type == 0) && {} || background.css}
          >
            <div>
              <FormMainView
                formFooter={formFooter}
                formHeader={formHeader}
                components={components}
                viewType={viewType}
                onSubmit={onSubmit}
                onValueChange={onValueChange}
                shortkey={rightLevel === 2 ? shortkey : ""}
                toggleFooterDisable={toggleFooterDisable}
              />
              {
                formHeader ?
                  <FBHeaderView data={formHeader.config} bottom={true} shortkey={rightLevel === 2 ? shortkey : ""} />
                  : null
              }
            </div>
          </div>
        )}
      </Consumer>
    );
  }
}